package com.sz.netty.server;

import com.sz.netty.config.NettyConfig;
import com.sz.netty.server.handler.BinaryDataHandler;
import com.sz.netty.server.handler.CardDataHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * Netty Server for handling binary data
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NettyServer {
    
    private final NettyConfig nettyConfig;
    
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ChannelFuture channelFuture;
    
    /**
     * Start Netty server
     */
    @PostConstruct
    public void start() {
        bossGroup = new NioEventLoopGroup(nettyConfig.getBossThreadCount());
        workerGroup = new NioEventLoopGroup(nettyConfig.getWorkerThreadCount());
        
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new ByteArrayDecoder())
                                    .addLast(new ByteArrayEncoder())
                                    .addLast(new CardDataHandler())  // Add CardDataHandler first to process card data
                                    .addLast(new BinaryDataHandler()); // BinaryDataHandler processes remaining data
                        }
                    });
            
            channelFuture = bootstrap.bind(nettyConfig.getPort()).sync();
            log.info("Netty server started on port {}", nettyConfig.getPort());
        } catch (InterruptedException e) {
            log.error("Failed to start Netty server", e);
            Thread.currentThread().interrupt();
        }
    }
    
    /**
     * Stop Netty server
     */
    @PreDestroy
    public void stop() {
        if (channelFuture != null) {
            channelFuture.channel().close();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        log.info("Netty server stopped");
    }
}